package com.example.sources.handler;

import com.example.custom.mybatis.entity.Userinfo;
import com.example.sources.Select;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liyuncong
 * @version 1.0
 * @file SelectHandler
 * @brief SelectHandler
 * @details Select处理器
 * @date 2022-11-14
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-11-14                  liyuncong          Created
 */
public class SelectHandler extends AbstractHandlerBase {

    @Override
    public String parseSql(Method method) {
        final Select annotation = method.getAnnotation(Select.class);
        if (null != annotation) {
            return annotation.value();
        }
        return null;
    }

    @Override
    public Object process(
        Method method, Object[] args, String oldSql, Connection connection
    ) throws Exception {
        final Map<String, Object> paramValueMappingMap =
            paramValueMappingMap(method.getParameters(), args);

        final Map<String, Object> sqlMap = parseSql(oldSql);

        final String newSql = (String) sqlMap.get("sql");
        final List<String> paramsIndex = (List<String>) sqlMap.get("params");

        final PreparedStatement statement = connection.prepareStatement(newSql);
        processSql(statement, paramValueMappingMap, paramsIndex);

        final ResultSet resultSet = statement.executeQuery();
        List<Userinfo> list = new ArrayList<>();
        while (resultSet.next()) {
            final int id = resultSet.getInt("id");
            final String username = resultSet.getString("username");
            final int age = resultSet.getInt("age");
            final int gender = resultSet.getInt("gender");
            final Userinfo userinfo = new Userinfo(id, username, age, gender);
            list.add(userinfo);
        }
        resultSet.close();
        statement.close();
        connection.close();
        return list;
    }
}
